package com.pig4cloud.pig.ads.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.ads.pig.mapper.AdVideoMapper;
import com.pig4cloud.pig.ads.pig.mapper.AdVideoPlatformMapper;
import com.pig4cloud.pig.api.dto.AdVideoAdsReportDTO;
import com.pig4cloud.pig.api.dto.AdVideoReport;
import com.pig4cloud.pig.api.entity.AdVideo;
import com.pig4cloud.pig.api.vo.*;
import com.pig4cloud.pig.ads.service.AdVideoService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * @author cx
 * @version 1.0.0
 * @ClassName AdVideoController.java
 * @createTime 2020年11月05日 14:05:00
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/advideo")
@Api(value = "advideo", tags = "视频管理模块")
public class AdVideoController {

	private final AdVideoMapper mapper;

	private final AdVideoService adVideoService;

	private final RemoteUserService remoteUserService;

	private final AdvService advService;

	private final AdVideoPlatformMapper adVideoPlatformMapper;

	/**
	 * 分页列表
	 * @param req
	 * @return
	 */
	@RequestMapping("/getPage")
	public R getPage(AdVideoVo req){
		//设置分页条件
		Page page = new Page();
		page.setSize(req.getSize());
		page.setCurrent(req.getCurrent());
		IPage<AdVideoVo> data = adVideoService.selectAdVideoListPage(req);
		return R.ok(data, "请求成功");
	}


	/**
	 * 已下线
	 * 视频列表（包含排序）
	 * @param req
	 * @return
	 */
	@RequestMapping("/getAdVideoSortList")
	public R getAdVideoSortList(AdVideoSortVo req){
		List<AdVideoAdsReportDTO> list = adVideoService.selectAdVideoSortList(req);
		return R.ok(list, "请求成功");
	}





	/**
	 * 根据id加载数据
	 * @param id
	 * @return
	 */
	@RequestMapping("/findById")
	public R findById(String id){
		if (StringUtils.isBlank(id)){
			return R.failed(null,"参数丢失");
		}
		AdVideo data = mapper.selectById(id);
		return R.ok(data, "请求成功");
	}

	@RequestMapping("/findByIds")
	public R getByVideoId(String platformVids) {
		AdVideoAdVo adVideoAdVo =  new AdVideoAdVo();
		if (StringUtils.isBlank(platformVids)) {
			return R.ok(adVideoAdVo);
		}
		adVideoAdVo = adVideoPlatformMapper.selectByKey(platformVids);
		if (Objects.isNull(adVideoAdVo)){
				return R.failed("视频和三方平台关联表无此视频");
		}
		return R.ok(adVideoAdVo);
	}

	/*@RequestMapping("/findByIds")
	public R getByVideoId(String[] platformVids) {
		List<AdVideoAdVo> adVideoAdVoList= Lists.newArrayList();
		if(platformVids == null || platformVids.length == 0){
			return R.ok(adVideoAdVoList);
		}
		for (String platformVid : platformVids) {
		     AdVideoAdVo adVideoAdVo = adVideoPlatformMapper.selectByKey(platformVid);
			if (Objects.isNull(adVideoAdVo)){
				return R.failed("视频和三方平台关联表无此视频");
			}
			adVideoAdVoList.add(adVideoAdVo);
		}
		return R.ok(adVideoAdVoList);
	}*/

	@RequestMapping("/edit")
	public R edit(AdVideo req){
		if (null == req || null == req.getId()){
			return R.failed(null,"参数丢失");
		}
		req.setUpdatetime(new Date());
		req.setUpdateuser(String.valueOf(SecurityUtils.getUser().getId()));
		int num = mapper.updateById(req);
		if (num > 0) {
			return R.ok(null,"修改成功");
		}
		return R.failed(null,"修改失败");
	}
	/**
	 * 批量删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/delById")
	public R del(String id){
		if (StringUtils.isBlank(id)){
			return R.failed(null,"参数丢失");
		}
		//设置where条件
		QueryWrapper<AdVideo> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", id);
		int num = mapper.delete(queryWrapper);
		if (num > 0) {
			return R.ok(null,"删除成功");
		}
		return R.failed(null,"删除失败");
	}
	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delByIds")
	public R delByIds(String[] ids){
		if (null == ids || ids.length == 0){
			return R.failed(null,"参数丢失");
		}
		List<String> idList = Arrays.asList(ids);
		int num = mapper.deleteBatchIds(idList);
		if (num > 0) {
			return R.ok(null,"批量删除成功");
		}
		return R.failed(null,"批量删除失败");
	}

	/**
	 * 视频上传保存
	 * @param file
	 * @return
	 */
	@RequestMapping("/uploadVideo")
	public R uploadVideo(MultipartFile[] file) {
		if (null == file || file.length == 0){
			return R.failed(null,"未获取到视频文件");
		}
		return adVideoService.uploadVideo(file);
	}

	/**
	 * 上传视频同时同步头条
	 * @param file
	 * @param req
	 * @return
	 */
	@RequestMapping("/uploadPushVideo")
	public R uploadPushVideo(MultipartFile[] file,AdVideoVo req){
		Map<String,Object> result = new HashMap<>();
		R r = adVideoService.uploadVideo(file);
		if (r.getCode() == 0 && null != r.getData()){
			List<AdVideo> adVideoList = JSON.parseArray(JSON.toJSONString(r.getData()),AdVideo.class);
			if (adVideoList.size() > 0){
				req.setIds(String.valueOf(adVideoList.get(0).getId()));
				R<Map<String,Object>> data = adVideoService.pushVideo(req);
				if (data.getCode() == 0){
					result.put("video",r.getData());//视频信息对象
					result.put("platform",data.getData());//推送三方平台信息
					return R.ok(result,"上传成功");
				}
				return R.failed(null,data.getMsg());
			}else{
				return R.failed(null,"未获取到视频信息");
			}
		}else{
			return R.failed(null,r.getMsg());
		}
	}

	/**
	 * 查看视频报表信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/findReport")
	public R findReportById(HttpServletRequest request){
		String vid = request.getParameter("id");
		String start_time = request.getParameter("startTime");
		String end_time = request.getParameter("endTime");
		try {
			if (StringUtils.isBlank(vid) || StringUtils.isBlank(start_time) || StringUtils.isBlank(end_time)){
				return R.failed(null,"参数异常");
			}
			start_time = start_time.replaceAll("-","");
			end_time = end_time.replaceAll("-","");
			Map<String,Object> param = new HashMap<>();
			param.put("vid",vid);
			param.put("start_time",Long.parseLong(start_time));
			param.put("end_time",Long.parseLong(end_time));
			R<List<AdVideoReport>> data = adVideoService.findReport(param);
			return R.ok(data.getData());
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(null,"系统异常");
		}

	}
	/**
	 * 获取制作人全部列表
	 * @return
	 */
	@RequestMapping("/getUserList")
	public R userList(){
		R<List<SysUser>> data = remoteUserService.getUserList(SecurityConstants.FROM_IN);
		if (0 == data.getCode()){
			return R.ok(data.getData(),"请求成功");
		}else{
			return R.failed(null,data.getMsg());
		}
	}

	/**
	 * 推送视频
	 * @param req
	 * @return
	 */
	@RequestMapping("/pushVideo")
	public R pushVideo(@RequestBody AdVideoVo req){
		R<Map<String,Object>> data = adVideoService.pushVideo(req);
		if (data.getCode() != 0){
			return R.failed(null,data.getMsg());
		}
		return R.ok(data.getData(),"操作成功");
	}

	/**
	 * 获取视频已推送的广告账户
	 * @param req
	 * @return
	 */
	@RequestMapping("/getPushAdList")
	public R getPushAdList(AdVideoPlatformVo req){
		if (StringUtils.isBlank(req.getId()) || StringUtils.isBlank(req.getType())){
			return R.failed(null,"参数丢失");
		}
		return adVideoService.getPushAdList(req);
	}

	/**
	 * 已下线
	 * 视频投放数据
	 * @param req
	 * @return
	 */
	@RequestMapping("/getAdVideoReport")
	public R getAdVideoReport(@Valid AdVideoReportVo req){
		//设置分页条件
		Page page = new Page();
		page.setSize(req.getSize());
		page.setCurrent(req.getCurrent());
		return adVideoService.getPrestoAdVideoReport(req);
	}

}
